package org.stvd.core.web.freemarker.support;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.stvd.core.web.freemarker.method.SystemDate;

import cn.org.rapid_framework.freemarker.directive.BlockDirective;
import cn.org.rapid_framework.freemarker.directive.ExtendsDirective;
import cn.org.rapid_framework.freemarker.directive.OverrideDirective;
import cn.org.rapid_framework.freemarker.directive.SuperDirective;
import freemarker.cache.TemplateLoader;
import freemarker.template.TemplateException;

public class FreeMarkerConfigurerEx extends FreeMarkerConfigurer {

    private String[] remotePaths = {};

    public void setRemotePaths(String[] remotePaths) {
        if (remotePaths != null) {
            this.remotePaths = Arrays.copyOf(remotePaths, remotePaths.length);
        }
    }

    @Override
    public void afterPropertiesSet() throws IOException, TemplateException {
        super.afterPropertiesSet();

        // 使用rapid-framework实现模版继承功能
        this.getConfiguration().setSharedVariable("block", new BlockDirective());
        this.getConfiguration().setSharedVariable("override", new OverrideDirective());
        this.getConfiguration().setSharedVariable("extends", new ExtendsDirective());
        this.getConfiguration().setSharedVariable("super", new SuperDirective());

        // 系统时间
        this.getConfiguration().setSharedVariable("SystemDate", new SystemDate());

        this.getConfiguration().setLocalizedLookup(false);
    }

    @Override
    protected void postProcessTemplateLoaders(List<TemplateLoader> templateLoaders) {
        // 增加远程加载模板模块
        for (String remotePath : remotePaths) {
            templateLoaders.add(new RemoteTemplateLoader(remotePath));
        }
        super.postProcessTemplateLoaders(templateLoaders);
    }

}
